#!/usr/bin/python
#coding:utf-8
import sys
sys.path.append('../')
from flask import Flask, render_template
from web_flask.app import app, socketio
import logging
import logging.handlers
import os
from flask_login import LoginManager, login_user, login_required, logout_user, UserMixin
from flask import request,redirect, url_for,send_from_directory

#<editor-fold desc="一般不改动 设置日志部分">

# 定义一个StreamHandler，将INFO级别或更高的日志信息打印到标准错误，并将其添加到当前的日志处理对象#
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

LOG_FILE = 'at_py.log'

handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5)  # 实例化handler
fmt = '%(asctime)s | %(filename)-12s:%(lineno)-5s | %(levelname)-8s | %(message)s'
datefmt = '%Y-%m-%d %H:%M:%S'

formatter = logging.Formatter(fmt, datefmt)  # 实例化formatter
handler.setFormatter(formatter)  # 为handler添加formatter
logger = logging.getLogger('at_py')  # 获取名为tst的logger
logger.addHandler(handler)  # 为logger添加handler
logger.setLevel(logging.DEBUG)
#</editor-fold>

#<editor-fold desc="一般不改动  验证登陆部分代码">

# 登陆相关
app.secret_key = os.urandom(10)  # 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

# flask_login 设置----------------------------------------------------------------------------
login_manager = LoginManager()
login_manager.session_protection = 'strong'   #'basic' 或'strong'
login_manager.init_app(app)
login_manager.login_view = 'weblogin'
login_manager.login_message = '请登录'



class User(UserMixin):
    def __init__(self, id, username, pwd):
        self.id = id
        self.name = username
        self.pwd = pwd

    def __repr__(self):
        return '<User %r>' % self.username


@login_manager.user_loader
def load_user(user_id):
    #print('登陆检测经过了%s' % user_id)
    if user_id == '1':
        return User('1', 'liuadong', '123')


# 设置flask_login 设置--------------------------------------------------------------------------------

# --------------------------------------------------------------------------登陆相关
@app.route('/weblogin', methods=['GET', 'POST'])
def weblogin():
    if request.method == 'GET':
        return '''
                           <form action="#" method="POST">
                       <span>请输入账号</span>
                       <input type="text" name="name" id="name" placeholder="name">
                       <span>请输入密码</span>
                       <input type="password" name="pw" id="pw" placeholder="password">
                       <input type="submit" name="submit">
                          </form>
                           '''
    print('经过没')
    name = request.form.get('name')
    user = User('1', 'liuadong', '123')
    if request.form.get('name') != user.name:
        return "用户名不存在"
    elif request.form.get('pw') != user.pwd:
        return '密码错误'
    else:
        login_user(user, remember=True)
        next_url = request.args.get('next')
        return redirect(next_url or url_for('login_success'))



# -----------------------------------退出
@app.route('/logout/')
@login_required
def logout():
    logout_user()
    return '已经退出登陆'


# ---------------------------------------------------------------------登陆相关

@app.errorhandler(404)
def page_not_found(error):
    # return render_template('page_not_found.html'),404
    return "未找到任何页面"


@app.route('/static/<path:path>')
@login_required
def send_js(path):
    return send_from_directory('static', path)


    # ---------------------------------------------------------------------静态相关


#</editor-fold>

from flask import session
from datetime import timedelta

app.permanent_session_lifetime = timedelta(minutes=10)
if __name__ == '__main__':
    socketio.run(app, debug=True, host='0.0.0.0',port=8000)  # , port=27017)
    #app.run(debug=True, port=5000)
    # socketio.run(app)

"""
使用flask 等于已经实现了多进程  也就是两个进程之间是分开的  一个专注于运行交易 一个专注于显示以及接受通讯
理论上还可以实现接口层(也就是传输层的分离)
如果计算繁杂了  理论上还可以在策略层再分开一层（https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386832973658c780d8bfa4c6406f83b2b3097aed5df6000）
主机分配计算任务到个个附机进程上，进程计算完毕之后再返回主机。
"""
